package com.atguigu.spzx.manager.service.Impl;

import com.atguigu.spzx.manager.properties.MinioProperties;
import com.atguigu.spzx.manager.service.FileUploadService;
import com.atguigu.spzx.service.exception.GuliException;
import io.minio.*;
import io.minio.errors.MinioException;
import jakarta.annotation.Resource;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.spzx.manager.service.Impl
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/2 16:32
 * @Version 1.0
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Resource
    private MinioProperties minioProperties;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            // minio的客户端
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpoint())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            // 判断桶是否已经存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // 如果不存在则创建
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            }
            // 文件上传
            // 组装文件名  ---> 目录/文件名
            String fileName = "";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String dir = simpleDateFormat.format(new Date());
            String originalFileName = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename();
            fileName = dir + "/" + originalFileName;
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            String fileUrl = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" +dir + "/" + originalFileName;
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
